package com.renyisima.wujiansima.demo.demo3;

import com.renyisima.wujiansima.demo.demo2.Student;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Demo3 {
    public static void main(String[] args) throws Exception {
        Student s = new Student();
        Student s1= new Student();
        setProperty(s,"age",23);
        setProperty(s,"name","伍鉴");
        System.out.println(s);
        Object age = getProperty(s1, "age");
        System.out.println(age);
    }
// 获得任意对象的值
    private static Object getProperty(Object obj,String name) throws Exception {
        Class clazz = obj.getClass();
        Field f = clazz.getDeclaredField(name);
        Class type = f.getType();
        String s = "get" + name.substring(0,1).toUpperCase() + name.substring(1);
        Method method = clazz.getMethod(s);
        Object invoke = method.invoke(obj);
        return invoke;
    }

    //     给任意对象的任意属性赋值
    private static void setProperty(Object obj,String name,Object value) throws Exception {
        Class clazz = obj.getClass();

        Field field = clazz.getDeclaredField(name);
        Class type = field.getType();
        String method = "set" + name.substring(0,1).toUpperCase() + name.substring(1);
        Method method1 = clazz.getMethod(method,type);
        method1.invoke(obj,value);
    }
}
